<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">






  
  
  <link rel="stylesheet" media="all" href="/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/logo.jpg?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/logo.jpg?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="C#,比特流,编码," />










<meta name="keywords" content="C#,比特流,编码">
<meta property="og:type" content="article">
<meta property="og:title" content="使用C#处理基于比特流的数据">
<meta property="og:url" content="http://durow.vip/2016/10/13/CS/使用C-处理基于比特流的数据/index.html">
<meta property="og:site_name" content="Durowの隅">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/1013/201610130000.png">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/1013/201610130301.png">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/1013/201610130302.png">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/1013/201610130401.png">
<meta property="og:updated_time" content="2018-03-23T05:53:42.262Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="使用C#处理基于比特流的数据">
<meta name="twitter:image" content="http://durow.gitee.io/source/images/2016/1013/201610130000.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"right","display":"always","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://durow.vip/2016/10/13/CS/使用C-处理基于比特流的数据/"/>





  <title>使用C#处理基于比特流的数据 | Durowの隅</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?b5605a7aa8d230851edcda67de588833";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Durowの隅</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">forever love, forever dream</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-sitemap">
          <a href="/sitemap.xml" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />
            
            站点地图
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="st-search-show-outputs">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <form class="site-search-form">
  <input type="text" id="st-search-input" class="st-search-input st-default-search-input" />
</form>

<script type="text/javascript">
  (function(w,d,t,u,n,s,e){w['SwiftypeObject']=n;w[n]=w[n]||function(){
    (w[n].q=w[n].q||[]).push(arguments);};s=d.createElement(t);
    e=d.getElementsByTagName(t)[0];s.async=1;s.src=u;e.parentNode.insertBefore(s,e);
  })(window,document,'script','//s.swiftypecdn.com/install/v2/st.js','_st');

  _st('install', 'jv23s59-xwQTfQjP6xPi','2.0.0');
</script>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://durow.vip/2016/10/13/CS/使用C-处理基于比特流的数据/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="durow">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/logo.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Durowの隅">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">使用C#处理基于比特流的数据</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-10-13T17:45:00+08:00">
                2016-10-13
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/C/" itemprop="url" rel="index">
                    <span itemprop="name">C#</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2016/10/13/CS/使用C-处理基于比特流的数据/" class="leancloud_visitors" data-flag-title="使用C#处理基于比特流的数据">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <p><img src="http://durow.gitee.io/source/images/2016/1013/201610130000.png" alt="ASP.NET"></p>
<a id="more"></a>
<h2 id="0x00-起因"><a href="#0x00-起因" class="headerlink" title="0x00 起因"></a>0x00 起因</h2><p>最近需要处理一些基于比特流的数据，计算机处理数据一般都是以byte（8bit）为单位的，使用BinaryReader读取的数据也是如此，即使读取bool型也是一个byte。不过借助于C#基础类库中提供的一些方法，也实现了对基于比特的数据的读取。任务完成后觉得基于比特的数据挺有意思，自己试了下用7比特和6比特编码常用ASCII字符。最后把一点新的写成博客，一方面做个记录，另一方面希望对有类似需求的园友有所帮助。</p>
<h2 id="0x01-比特流数据的读取"><a href="#0x01-比特流数据的读取" class="headerlink" title="0x01 比特流数据的读取"></a>0x01 比特流数据的读取</h2><p>假设我们有一个byte b = 35，而我们需要把其中的前4bit和后4bit分别读取为两个数字，那么应该怎么做呢。虽然没有在基础类库中找到现成的方法，但用二进制字符串中转一下，分两步也可以做到。</p>
<ul>
<li>1、先把b表示为二进制字符串00100011</li>
<li>2、分别取其前后4bit转为数字，核心方法就是：</li>
</ul>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Convert.ToInt32(<span class="string">"0010"</span>);</span><br></pre></td></tr></table></figure>
<p>这样就实现了基于比特的数据读取了。</p>
<p>关于第一步中把byte转化为二进制字符串有很多种方法，</p>
<ul>
<li>1、最简单的Convert.ToString(b,2)。不够8位就在高位用0补足。</li>
<li>2、也可以把byte分别与1,2,4,8 … 128做与运算，由低到高取出各位。</li>
<li>3、也可以把byte和32做与运算，然后把byte左移再次与128做与运算。</li>
</ul>
<p>其中第一种方法会产生大量的字符串对象，在第2、3种方法没有找到太大区别，我选择的3，纯靠感觉。代码如下：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">char</span>[] <span class="title">ByteToBinString</span>(<span class="params"><span class="keyword">byte</span> b</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">　　<span class="keyword">var</span> result = <span class="keyword">new</span> <span class="keyword">char</span>[<span class="number">8</span>];</span><br><span class="line">　　<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">8</span>; i++)</span><br><span class="line">　　&#123;</span><br><span class="line">　　　　<span class="keyword">var</span> temp = b &amp; <span class="number">128</span>;</span><br><span class="line">　　　　result[i] = temp == <span class="number">0</span> ? <span class="string">'0'</span> : <span class="string">'1'</span>;</span><br><span class="line">　　　　b = (<span class="keyword">byte</span>)(b &lt;&lt; <span class="number">1</span>);</span><br><span class="line">　　&#125;</span><br><span class="line">　　<span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>为了能将byte[]转化为二进制字符串，可以</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">Public <span class="keyword">string</span> <span class="title">BitReader</span>(<span class="params"><span class="keyword">byte</span>[] data</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    BinString = <span class="keyword">new</span> StringBuilder(data.Length * <span class="number">8</span>);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; data.Length; i++)</span><br><span class="line">    &#123;</span><br><span class="line">         BinString.Append(ByteToBinString(data[i]));</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> BinString.ToString();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样一来当拿到byte[]数据时,可以转换为二进制字符串保存起来，根据偏移的bit位置和bit长度从中读取二进制字符串，并转换为bool，Int16，Int32等。基于这个思路，可以写一个BitReader类，其中用StringBuilder存储二进制字符串，并提供Read方法从二进制字符串中读取数据。为了能够更好的处理数据流，在此基础上添加一个Position记录当前偏移，当使用某些Read方法读取数据时，Position也会相应移动。例如使用ReadInt16读取数据，BitReader会从Position当前位置，读取16bit并转换为Int16返回，同时Position向后移动16bit。区分方式就是当读取数据时需要指定起始的偏移位置时，Position不移动，直接从当前Position读取时Position移动，BitReader类部分代码如下：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">BitReader</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">readonly</span> StringBuilder BinString;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> Position &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BitReader</span>(<span class="params"><span class="keyword">byte</span>[] data</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        BinString = <span class="keyword">new</span> StringBuilder(data.Length * <span class="number">8</span>);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; data.Length; i++)</span><br><span class="line">        &#123;</span><br><span class="line">            BinString.Append(ByteToBinString(data[i]));</span><br><span class="line">        &#125;</span><br><span class="line">        Position = <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">byte</span> <span class="title">ReadByte</span>(<span class="params"><span class="keyword">int</span> offset</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> bin = BinString.ToString(offset, <span class="number">8</span>);</span><br><span class="line">        <span class="keyword">return</span> Convert.ToByte(bin, <span class="number">2</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">byte</span> <span class="title">ReadByte</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> result = ReadByte(Position);</span><br><span class="line">        Position += <span class="number">8</span>;</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">ReadInt</span>(<span class="params"><span class="keyword">int</span> offset, <span class="keyword">int</span> bitLength</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> bin = BinString.ToString(offset, bitLength);</span><br><span class="line">        <span class="keyword">return</span> Convert.ToInt32(bin, <span class="number">2</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">ReadInt</span>(<span class="params"><span class="keyword">int</span> bitLength</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> result = ReadInt(Position, bitLength);</span><br><span class="line">        Position += bitLength;</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">char</span>[] <span class="title">ByteToBinString</span>(<span class="params"><span class="keyword">byte</span> b</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> result = <span class="keyword">new</span> <span class="keyword">char</span>[<span class="number">8</span>];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">8</span>; i++)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">var</span> temp = b &amp; <span class="number">128</span>;</span><br><span class="line">            result[i] = temp == <span class="number">0</span> ? <span class="string">'0'</span> : <span class="string">'1'</span>;</span><br><span class="line">            b = (<span class="keyword">byte</span>)(b &lt;&lt; <span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">     &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>使用BitReader按照4bit从byte[] buff= {35,12};中读取数据可以这样：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> reader = <span class="keyword">new</span> BitReader(buff); <span class="comment">//二进制字符串为0010001100001100</span></span><br><span class="line"><span class="keyword">var</span> num1 = reader.ReadInt(<span class="number">4</span>);   <span class="comment">//从当前Position读取4bit为int，Position移动4bit，结果为2，当前Position=4</span></span><br><span class="line"><span class="keyword">var</span> num2 = reader.ReadInt(<span class="number">5</span>,<span class="number">6</span>);  <span class="comment">//从偏移为5bit的位置读取6bit为int，Position不移动，结果为48，当前Position=4</span></span><br><span class="line"><span class="keyword">var</span> b = reader.ReadBool();  <span class="comment">//从当前Position读取1bit为bool，Position移动1bit，结果为False，当前Position=5</span></span><br></pre></td></tr></table></figure>
<h2 id="0x02-比特流数据的写入"><a href="#0x02-比特流数据的写入" class="headerlink" title="0x02 比特流数据的写入"></a>0x02 比特流数据的写入</h2><p>把数据写入比特流就是一个相反的过程，我们用BitWriter类实现，在其中存储StringBuilder保存二进制字符串，当写入数据时，需要传入数据并指定保存这个数据所需要的bit数。当写入完毕后可以将StringBuilder中保存的二进制字符串按照8bit转换为byte[]并返回。BitWriter的核心部分如下：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">BitWriter</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">readonly</span> StringBuilder BinString;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BitWriter</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        BinString = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BitWriter</span>(<span class="params"><span class="keyword">int</span> bitLength</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> <span class="keyword">add</span> = <span class="number">8</span> - bitLength % <span class="number">8</span>;</span><br><span class="line">        BinString = <span class="keyword">new</span> StringBuilder(bitLength + <span class="keyword">add</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">WriteByte</span>(<span class="params"><span class="keyword">byte</span> b, <span class="keyword">int</span> bitLength=<span class="number">8</span></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> bin = Convert.ToString(b, <span class="number">2</span>);</span><br><span class="line">        AppendBinString(bin, bitLength);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">WriteInt</span>(<span class="params"><span class="keyword">int</span> i, <span class="keyword">int</span> bitLength</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> bin = Convert.ToString(i, <span class="number">2</span>);</span><br><span class="line">        AppendBinString(bin, bitLength);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">WriteChar7</span>(<span class="params"><span class="keyword">char</span> c</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> b = Convert.ToByte(c);</span><br><span class="line">        <span class="keyword">var</span> bin = Convert.ToString(b, <span class="number">2</span>);</span><br><span class="line">        AppendBinString(bin, <span class="number">7</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">byte</span>[] <span class="title">GetBytes</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        Check8();</span><br><span class="line">        <span class="keyword">var</span> len = BinString.Length / <span class="number">8</span>;</span><br><span class="line">        <span class="keyword">var</span> result = <span class="keyword">new</span> <span class="keyword">byte</span>[len];</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; len; i++)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">var</span> bits = BinString.ToString(i * <span class="number">8</span>, <span class="number">8</span>);</span><br><span class="line">            result[i] = Convert.ToByte(bits, <span class="number">2</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">string</span> <span class="title">GetBinString</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        Check8();</span><br><span class="line">        <span class="keyword">return</span> BinString.ToString();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">AppendBinString</span>(<span class="params"><span class="keyword">string</span> bin, <span class="keyword">int</span> bitLength</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (bin.Length &gt; bitLength)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> Exception(<span class="string">"len is too short"</span>);</span><br><span class="line">        <span class="keyword">var</span> <span class="keyword">add</span> = bitLength - bin.Length;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="keyword">add</span>; i++)</span><br><span class="line">        &#123;</span><br><span class="line">            BinString.Append(<span class="string">'0'</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        BinString.Append(bin);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">Check8</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> <span class="keyword">add</span> = <span class="number">8</span> - BinString.Length % <span class="number">8</span>;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="keyword">add</span>; i++)</span><br><span class="line">        &#123;</span><br><span class="line">            BinString.Append(<span class="string">"0"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>下面举个简单的例子：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> writer = <span class="keyword">new</span> BitWriter();</span><br><span class="line">writer.Write(<span class="number">12</span>,<span class="number">5</span>);  <span class="comment">//把12用5bit写入，此时二进制字符串为：01100</span></span><br><span class="line">writer.Write(<span class="number">8</span>,<span class="number">16</span>);  <span class="comment">//把8用16bit写入，此时二进制字符串为：011000000000000001000</span></span><br><span class="line"><span class="keyword">var</span> result = writer.GetBytes(); <span class="comment">//8bit对齐为011000000000000001000000</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//返回结果为[96,0,64]</span></span><br></pre></td></tr></table></figure>
<h2 id="0x03-7比特字符编码"><a href="#0x03-7比特字符编码" class="headerlink" title="0x03 7比特字符编码"></a>0x03 7比特字符编码</h2><p>我们常用的ASCII字符是使用8bit编码的，但其中真正常用的那些字符只有7bit，最高位为0，所以对于一篇英文文章，我们可以使用7bit重新编码而不损失信息。编码的过程就是把文章字符依次取出，并用BitWriter按照7bit写入，最后获取新编码的byte[]。为了能够正确读取，我们规定当读到8bit数据为2时代表数据开始，接下来16bit数据为后面字符个数。代码如下：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">byte</span>[] <span class="title">Encode</span>(<span class="params"><span class="keyword">string</span> text</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">var</span> len = text.Length * <span class="number">7</span> + <span class="number">24</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> writer = <span class="keyword">new</span> BitWriter(len);</span><br><span class="line">    writer.WriteByte(<span class="number">2</span>);</span><br><span class="line">    writer.WriteInt(text.Length, <span class="number">16</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; text.Length; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">var</span> b = Convert.ToByte(text[i]);</span><br><span class="line">        writer.WriteByte(b, <span class="number">7</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> writer.GetBytes();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>同样读取数据的时候，我们先寻找开始标识符，然后读出字符个数，根据字符个数依次读取字符，代码如下：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">string</span> <span class="title">Decode</span>(<span class="params"><span class="keyword">byte</span>[] data</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">var</span> reader = <span class="keyword">new</span> BitReader(data);</span><br><span class="line">    <span class="keyword">while</span> (reader.Remain &gt; <span class="number">8</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">var</span> start = reader.ReadByte();</span><br><span class="line">        <span class="keyword">if</span> (start == <span class="number">2</span>)</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">var</span> len = reader.ReadInt(<span class="number">16</span>);</span><br><span class="line">    <span class="keyword">var</span> result = <span class="keyword">new</span> StringBuilder(len);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; len; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">var</span> b = reader.ReadInt(<span class="number">7</span>);</span><br><span class="line">        <span class="keyword">var</span> ch = Convert.ToChar(b);</span><br><span class="line">        result.Append(ch);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> result.ToString();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>由于数据头的存在，当编码几个字符时编码后数据反而更长了</p>
<p><img src="http://durow.gitee.io/source/images/2016/1013/201610130301.png" alt="ASP.NET"></p>
<p>不过随着字符越多，编码后节省的越多。</p>
<p><img src="http://durow.gitee.io/source/images/2016/1013/201610130302.png" alt="ASP.NET"> </p>
<h2 id="0x04-6比特字符编码"><a href="#0x04-6比特字符编码" class="headerlink" title="0x04 6比特字符编码"></a>0x04 6比特字符编码</h2><p>从节省数据量的角度，如果允许损失部分信息，例如损失掉字母大小写，是可以进一步减少编码所需比特数的。26个字母+10个数字+符号，可以用6bit（64）进行编码。不过使用这种编码方式就不能用ASCII的映射方式了，我们可以自定义映射，例如0-10映射为十个数字等等，也可以使用自定义的字典，也就是传说中的密码本。经常看国产谍战片的应该都知道密码本吧，密码本就是一个字典，把字符进行重新映射获取明文，算是简单的单码替代，加密强度很小，在获取足量数据样本后基于统计很容易就能破解。下面我们就尝试基于自定义字典用6bit重新编码。</p>
<h3 id="编码"><a href="#编码" class="headerlink" title="编码"></a>编码</h3><p>仍然像7bit编码那样写入消息头，然后依次取出文本中的字符，从字典中找到对应的数字，把数字按照6bit长度写入到BitWriter</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">byte</span>[] <span class="title">Encode</span>(<span class="params"><span class="keyword">string</span> text</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    text = text.ToUpper();</span><br><span class="line">    <span class="keyword">var</span> len = text.Length * <span class="number">6</span> + <span class="number">24</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> writer = <span class="keyword">new</span> BitWriter(len);</span><br><span class="line">    writer.WriteByte(<span class="number">2</span>);</span><br><span class="line">    writer.WriteInt(text.Length, <span class="number">16</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; text.Length; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">var</span> index = GetChar6Index(text[i]);</span><br><span class="line">        writer.WriteInt(index, <span class="number">6</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> writer.GetBytes();</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">GetChar6Index</span>(<span class="params"><span class="keyword">char</span> c</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">64</span>; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">if</span> (Dict.Custom[i] == c)</span><br><span class="line">            <span class="keyword">return</span> i;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">10</span>; <span class="comment">//return *</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="解码"><a href="#解码" class="headerlink" title="解码"></a>解码</h3><p>解码也很简单，找到消息头，依次按照6bit读取数据，并从字典中找到对应的字符：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">string</span> <span class="title">Decode</span>(<span class="params"><span class="keyword">byte</span>[] data</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">var</span> reader = <span class="keyword">new</span> BitReader(data);</span><br><span class="line">    <span class="keyword">while</span>(reader.Remain &gt; <span class="number">8</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">var</span> start = reader.ReadByte();</span><br><span class="line">        <span class="keyword">if</span> (start == <span class="number">2</span>)</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">var</span> len = reader.ReadInt(<span class="number">16</span>);</span><br><span class="line">    <span class="keyword">var</span> result = <span class="keyword">new</span> StringBuilder(len);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; len; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">var</span> index = reader.ReadInt(<span class="number">6</span>);</span><br><span class="line">        <span class="keyword">var</span> ch = Dict.Custom[index];</span><br><span class="line">        result.Append(ch);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> result.ToString();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>同样一段文本用6bit自定义字典编码后数据长度更短了，不过损失了大小写和换行等格式。</p>
<p><img src="http://durow.gitee.io/source/images/2016/1013/201610130401.png" alt="ASP.NET"></p>
<p>如果从加密的角度考虑，可以设置N个自定义字典（假设10个），在消息头中用M bit（例如4bit）表示所用的字典。这样在每次编码时随机选择一个字典编码，解码时根据4bit数据选择相应字典解码，并且定时更换字典可以增大破解难度。感兴趣的园友可以自行尝试。</p>
<h2 id="0x05-写在最后"><a href="#0x05-写在最后" class="headerlink" title="0x05 写在最后"></a>0x05 写在最后</h2><p>以上是我处理比特流数据的一点心得，仅仅是我自己能想到的一种方法，满足了我的需求。如果有更效率的更合理的方法，希望赐教。另外编码和解码的两个例子是出于有趣写着玩的，在实际中估计也用不到。毕竟现在带宽这么富裕，数据加密也有N种可靠的多的方式。</p>
<p>示例代码：<a href="https://github.com/durow/TestArea/tree/master/BitStream" target="_blank" rel="noopener">https://github.com/durow/TestArea/tree/master/BitStream</a></p>
<p>关于基于比特流的数据读取封装成了库</p>
<p>安装：<code>PM&gt; Install-Package Ayx.BitIO</code></p>
<p>项目地址：<a href="https://github.com/durow/Ayx.BitIO" target="_blank" rel="noopener">https://github.com/durow/Ayx.BitIO</a></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>如果觉得有用请打赏一杯咖啡，谢谢 :P</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/WeChatPay.png" alt="durow 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/AliPay.jpg" alt="durow 支付宝"/>
        <p>支付宝</p>
      </div>
    

    
      <div id="bitcoin" style="display: inline-block">
        <img id="bitcoin_qr" src="/images/BitcoinPay.png" alt="durow 比特币"/>
        <p>比特币<br>地址:1433nFc4GmHj1gnXdhzA4T944WqSdBajuo</p>
      </div>
    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    durow
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://durow.vip/2016/10/13/CS/使用C-处理基于比特流的数据/" title="使用C#处理基于比特流的数据">http://durow.vip/2016/10/13/CS/使用C-处理基于比特流的数据/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/C/" rel="tag"># C#</a>
          
            <a href="/tags/比特流/" rel="tag"># 比特流</a>
          
            <a href="/tags/编码/" rel="tag"># 编码</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/09/09/NetCore/ASP-NET-Core中的日志（2）集成第三方日志工具/" rel="next" title="ASP.NET Core中的日志（2）集成第三方日志工具">
                <i class="fa fa-chevron-left"></i> ASP.NET Core中的日志（2）集成第三方日志工具
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/10/24/NetCore/ASP-NET-Core-MVC中的路由（1）路由配置基础/" rel="prev" title="ASP.NET Core MVC中的路由（1）路由配置基础">
                ASP.NET Core MVC中的路由（1）路由配置基础 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=2159540" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNTAyNi8xMTU2Mg=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/logo.jpg"
                alt="durow" />
            
              <p class="site-author-name" itemprop="name">durow</p>
              <p class="site-description motion-element" itemprop="description">热爱生活 热爱学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">53</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">42</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="http://www.qq.com" target="_blank" title="16141860">
                      
                        <i class="fa fa-fw fa-qq"></i>16141860</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:durow@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/durow" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/durow" target="_blank" title="Weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>Weibo</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://space.bilibili.com/13399420/" target="_blank" title="Bilibili">
                      
                        <i class="fa fa-fw fa-tv"></i>Bilibili</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.twitter.com/durow1984" target="_blank" title="Twitter">
                      
                        <i class="fa fa-fw fa-twitter"></i>Twitter</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-heart"></i>
                好站推荐
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://cnblogs.com/" title="博客园" target="_blank">博客园</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#0x00-起因"><span class="nav-number">1.</span> <span class="nav-text">0x00 起因</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x01-比特流数据的读取"><span class="nav-number">2.</span> <span class="nav-text">0x01 比特流数据的读取</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x02-比特流数据的写入"><span class="nav-number">3.</span> <span class="nav-text">0x02 比特流数据的写入</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x03-7比特字符编码"><span class="nav-number">4.</span> <span class="nav-text">0x03 7比特字符编码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x04-6比特字符编码"><span class="nav-number">5.</span> <span class="nav-text">0x04 6比特字符编码</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#编码"><span class="nav-number">5.1.</span> <span class="nav-text">编码</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#解码"><span class="nav-number">5.2.</span> <span class="nav-text">解码</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x05-写在最后"><span class="nav-number">6.</span> <span class="nav-text">0x05 写在最后</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">durow</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">47.2k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>



  <div class="footer-custom">Hosted by <a target="_blank" href="https://coding.net/pages" style="font-weight:bold">Coding Pages</a></div>


        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("Ai37u86U95uCssl57jjMliaH-gzGzoHsz", "QeIwQbw9Ndwl2sh4uawjySJJ");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "default";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "middleRight";
      
          pbOptions.networks = "Wechat,Weibo,Douban,QQZone,Evernote,Twitter";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
  </script>

  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
